package com.example.demo.crc16;

import cn.hutool.core.util.HexUtil;

/**
 * <pre>
 *  描述:
 * </pre>
 *
 * @author godelgnis(wujiaer)
 * @version 1.0.0
 * @date 2022/1/19 11:42
 */
public class EccCrc {

    public static void main(String[] args) {
        String hexStr = "05 01 C1 00 B8 00";
        hexStr = "07 01 C0 B1 03 00 BB D0";
        byte[] data = HexUtil.decodeHex(hexStr);
        int crc = crc(data, 0, data.length - 2);
        //int crc = Crc16(data, 0, data.length - 2);
        byte[] bytes = HexUtil.decodeHex("BB");
        System.out.println(bytes[0]);
        byte crc1High = (byte) ((crc & 0xFF00) >> 8);
        System.out.println(crc1High);
        byte crc2Low = (byte) (crc & 0xFF);
        System.out.println(HexUtil.toHex(crc));
        System.out.println(Integer.toHexString(crc1High));
        System.out.println(HexUtil.toHex(crc2Low));

        System.out.println(getCRC(data, data.length-2));
    }


    public static String getCRC(byte[] bytes, int len) {
        int crc = 0x0000ffff;
        int polynomial = 0x0000a001;

        int i, j;
        for (i = 0; i < len; i++) {
            crc ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((crc & 0x00000001) != 0) {
                    crc >>= 1;
                    crc ^= polynomial;
                } else {
                    crc >>= 1;
                }
            }
        }
        System.out.println("高位" + Integer.toHexString(crc >>> 8));
        System.out.println("低位" + Integer.toHexString(crc & 0x00FF));
        return Integer.toHexString(crc);
    }


    private static int crc(byte[] arr, int startIdx, int len) {
        int crcc = 0xFFFF;
        for (int j = startIdx; j <= len - 1; j++) {
            crcc = crcc ^ Byte.toUnsignedInt(arr[j]);
            for (int i = 0; i < 8; i++) {
                int it = crcc & 1;

                if (it == 1) {
                    crcc = crcc >> 1;
                    crcc = crcc ^ 0xA001;
                } else {
                    crcc = crcc >> 1;
                }
            }
        }
        return crcc;
    }

}
